package com.example.s08restful_sagger.controller;

import com.example.s08restful_sagger.common.BaseResult;
import com.example.s08restful_sagger.pojo.Message;
import com.example.s08restful_sagger.service.IMessageService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @auther zhangming
 * @date 2022/4/3 15:13
 */
@Api(value = "消息", description = "消息接口") //swagger注解
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private IMessageService messageService;

    // 查找
    @ApiOperation(
            value = "消息列表",
            notes = "完整的消息内容列表",
            produces = "application/json, application/xml",
            consumes = "application/json, application/xml",
            response = List.class)
    @GetMapping("/")
    public BaseResult<List<Message>> list() {
        List<Message> all = messageService.findAll();
        return BaseResult.success(all);
    }

    @GetMapping("/{id}")
    public BaseResult<Message> findOne(@PathVariable Long id) {
        Message byId = messageService.findById(id);
        return BaseResult.success(byId);
    }

    // 参数在请求体 json格式
    @ApiOperation(value = "添加消息", notes = "根据参数创建消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "消息 ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "text", value = "正文", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "summary", value = "摘要", required = false, dataType = "String", paramType = "query"),
    })
    @PostMapping("/")
    public BaseResult<Message> save(@RequestBody Message message) {
        messageService.save(message);
        return BaseResult.success(message);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        messageService.removeById(id);
    }

    @PutMapping
    public BaseResult<Message> update(@RequestBody Message message) {
        messageService.updateById(message);
        return BaseResult.success(message);
    }

    // 使用 put 请求进行修改
    @PutMapping(value = "message/{id}")
    @ApiOperation(value = "修改消息", notes = "根据参数修改消息")
    @ApiResponses({
            @ApiResponse(code = 100, message = "请求参数有误"),
            @ApiResponse(code = 101, message = "未授权"),
            @ApiResponse(code = 103, message = "禁止访问"),
            @ApiResponse(code = 104, message = "请求路径不存在"),
            @ApiResponse(code = 200, message = "服务器内部错误")
    })
    public BaseResult<Message> modify(@PathVariable Long id, @RequestBody Message message) {
        message.setId(id);
        this.messageService.updateById(message);
        return BaseResult.success(message);
    }

}
